(function (){
juicer.set({
	'tag::operationOpen': '<!--@',
	'tag::operationClose': '-->',
	'tag::interpolateOpen': '?{',
	'tag::interpolateClose': '}',
	'tag::noneencodeOpen': '!{',
	'tag::noneencodeClose': '}',
	'tag::commentOpen': '{#',
	'tag::commentClose': '}'
});
})();

var SC = {
	FAILED: -1, SUCCESS: 0,
	MSG: {'-1': '网络故障／服务异常', 0: '成功！'}
};

var URIHandler = {
	forward: function (val, data, form){
		window.location.href = juicer(val, data);
	},
	eval: function (val, data, form){
		eval(val);
	},
	render: function (val, data, form){
		var a = val.split('|');
		if (a.length == 1) {
			$(val).each(function (){
				var _this = $(this), tpl = _this.data('tpl');
				tpl || _this.data('tpl', tpl = _this.html());
				_this.html(juicer(tpl, {data:data})).removeClass('hide');
			});
		}
	}
};

var Utils = {
	func: function (name, caller){
		var fun ;
		if (!name || typeof (fun = window[name]) != 'function') return null;
		return caller ? function (){return fun.apply(caller, arguments)} : fun;
	},
	uri: function (str){
		if (!str) return { protocol:null, value:''};
		var i = str.indexOf(':');
		if (i == -1) return {protocol:null, value:str};
		else return {protocol:str.substring(0, i), value:str.substring(i + 1)};
	},
	handle: function (uri, data, form){
		var f = URIHandler[uri.protocol];
		f && f(uri.value, data, form);
	},
	ajax: function (type, url, callback, data, contentType, cache, async){
		var options = {'url':url, 'data':data, 'contentType':contentType, 'cache':!(cache === false), 'async':!(async === false), 'type':type, 'dataType':'text'};
		options.complete = function(xhr, st) {
			var obj = {'code': SC.FAILED, 'msg': SC.MSG['-1']};
			if (st == 'success') try { obj = JSON.parse(xhr.responseText); } catch (e) { obj.msg = e.toString(); }
			callback && callback(obj);
		};
		$.ajax(options);
	}
};

var E = {
	submit: function (form){
		form.find('.btn-submit').attr('disabled', true);
		// 去除输入项两端空白
		form.find(':text,:password').not(':disabled,[readonly]').each(function (){
			var i = $(this), val = $.trim(i.val());
			(i.val().length == val.length) || i.val(val);
		});
		var validate = function (){
			var errorPlacement = function (e, i){
				i.closest('.form-group').addClass('has-error');
				i.parent().append(e);
			}
			var success = function (l){
				l.closest('.form-group').removeClass('has-error');
				l.remove();
			}
			var options = {'focusInvalid':false, 'focusCleanup':true, 'errorPlacement':errorPlacement, 'success':success};
			form.validate(options);
			return form.valid();
		}
		// 隐藏error-target
		form.find('.alert-danger, .alert-success').empty().hide();
		if (!validate()) {
			form.find('.btn-submit').attr('disabled', false);
			return false;
		}
		var callback = function (obj){
			var uri;
			if (obj.code == SC.SUCCESS) {
				uri = form.data('success');
				form.find('.alert-success').html(SC.MSG[SC.SUCCESS]).show();
			} else {
				uri = form.data('error');
				form.find('.alert-danger').html(obj.msg).show();
			}
			if (uri) {
				uri = Utils.uri(uri);
				uri.protocol = uri.protocol ? uri.protocol : 'forward';
				Utils.handle(uri, obj.data, form);
			}
			form.find('.btn-submit').attr('disabled', false);
		}
		var enctype = form.attr('enctype');
		var method = form.attr('method');
		var action = form.attr('action');
		var data = form.serializeJSON();
		form.find('[type=password]').each(function (){
			data[this.name] = $.md5(this.value);
		});
		if ('application/json' == enctype) {
			data = JSON.stringify(data);
			method = 'POST';
		}
		Utils.ajax(method, action, callback, data, enctype, false, false);
	}
};

var DT = {
	queryParams: function (params){
		params.pageNumber = params.offset / params.limit;
		params.pageSize = params.limit;
		params.uuid = params.search ? params.search : '';
		return params;
	},
    responseHandler: function (res){
    	res.total = res.data.totalElements;
    	res.rows = res.data.content;
    	return res;
    },
    indexFormatter: function formatter(value, row, index, field) {
    	return index + 1;
    }
};

function resizeContent(){
	$(document).find('.content').css('min-height', function (){
		return $(document).height() -  $(this).offset().top -30;
	});
}

$(document).ready(function (){
	$('form .alert-danger,form .alert-success').empty().hide();
	$(document).on('click', 'form .btn-submit', function (){
		var form = $(this).closest('form');
		E.submit(form);
	});
	resizeContent();
	window.resize = resizeContent;
});